package token

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

const (
	// default 2 hours.
	accessTokenTimeout = time.Hour * 24 * 7
	// cache user token 48小时
	AuthCacheTimeoutUnix = 60 * 60 * 24 * 2
	// 盐码
	JwtSecret = "&WJof0jaY4ByTHR2"
	//
	issuer = "SHOP-SECURITY"
	//
	AuthCacheSecret = "Big_bang"
)

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

type Claims struct {
	UserId string `json:"userId"`
	jwt.StandardClaims
}

func GenerateAccessToken(subject, userId string) (int64, string, error) {
	expire := time.Now().Add(accessTokenTimeout)
	accessTokenClaims := Claims{
		UserId: userId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expire.Unix(),
			Issuer:    issuer,
			Subject:   subject,
		},
	}
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS384, accessTokenClaims)
	signedString, err := tokenClaims.SignedString([]byte(JwtSecret))
	return expire.Unix(), signedString, err
}

func ParseToken(secret, token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})

	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid

	}
}
